package com.bite.user.listener;


import com.bite.common.constant.Constants;
import com.bite.common.utils.JsonUtil;
import com.bite.common.utils.Mail;
import com.bite.user.dataobject.UserInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class UserQueueListener {

    @Autowired
    private Mail mail;


    @RabbitListener(queues = Constants.USER_QUEUE_NAME)
    public void handler(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            String body = new String(message.getBody());
            log.info("用户队列消息消费成功，消息内容：{}",body);
            UserInfo userInfo= JsonUtil.parseJson(body, UserInfo.class);
            mail.send(userInfo.getEmail(),"注册成功",buildContent(userInfo.getUserName()));
            //确认消息
            channel.basicAck(deliveryTag,true);
        }catch (Exception e){
            log.error("用户队列消息消费失败",e);
            //拒绝消息
            channel.basicNack(deliveryTag,true,true);
        }


    }

    public String buildContent(String userName) {
        StringBuilder content = new StringBuilder();
        content.append("恭喜您，").append(userName).append("，注册成功！").append("\n");
        content.append("欢迎来到我们的博客社区！").append("\n");
        content.append("您可以登录我们的博客社区，查看更多的内容！").append("\n");
        content.append("http://localhost:8080");
        return content.toString();
    }
}
